<?php

class Ext_Model_WebServiceClient
{

    protected $_model = null;
    protected $_localClass = null;

    function __construct() {
        $this->setModel();
    }

    function  __call($name, $args) {
        if ( empty( $this->_model ) ) {
            throw new Exception( 'Model class name must be declared');
        }

        if ( $this->_localClass != null ) {
            if ( ! method_exists( $this->_localClass, $name ) ) {
                throw new Exception("Method $name don't exists in class " . $this->_model );
            }
            return call_user_func_array(array( $this->_localClass, $name ), $args );
        }
        return call_user_func( array( $this->_client, $name ), $args );
    }

    public function getModel() {
        return $this->_model;
    }

    public function setModel( $model = null ) {

        if ( $model != null ) {
            $this->_model = $model;
        }
        if ( class_exists( $this->_model ) ) {
            $this->_localClass = new $this->_model;
        } else {
            $config = Zend_Registry::get( 'config' );
            if (! isset( $config->webServices ) || ! isset( $config->webServices->{$this->_model} )) {
                throw new Exception("Remote webservice " . $this->_model . " must be configured in config");
            }
            $this->_client = new Zend_Soap_Client( $config->webServices->{$this->_model} );
        }
    }
}
